<?php
/**
 * Created by PhpStorm.
 * User: liuhongchuan
 * Date: 2018/4/25
 * Time: 18:11
 */
namespace app\operation\controller;

use app\common\controller\OperationBase;

class Shop extends OperationBase {

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 店铺列表
     */
    public function index()
    {
        $auth_group = sp_get_auth_menu_3("20001000");
        $shops = db("shop")->where(array("parent_id" => array("eq", 0)))->order("parent_id desc, shop_name desc")->column("id, shop_name");
        $api_versions = db("api_template")->field("id, name, api_version")->select();
        $this->assign("api_versions", $api_versions);
        $this->assign("shops", $shops);

        $this->assign("menus", $auth_group);
        echo $this->fetch();
    }

    /**
     * 店铺数据
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function ajaxIndex()
    {
        $shop_id = input("shop_id/d");
        $shop_name = input("shop_name/s");
        $api_version = input("api_version/s");
        $where["parent_id"] = array("gt", 0);
        if (!empty($shop_id)) {
            $where["parent_id"] = array("eq", $shop_id);
        }
        if (!empty($shop_name)) {
            $where["shop_name"] = array("like", "%{$shop_name}%");
        }
        if (!empty($api_version)) {
            $where["api_version"] = array("eq", $api_version);
        }
        $list = db("shop")->where($where)->order($this->get_order())->limit($this->get_limit())->select();
        $total = db("shop")->where($where)->count(1);
        $draw = input("draw",0) + 1; //请求时间

        $parents = db("shop")->where(array("parent_id" => array("eq", 0)))->column("shop_name","id");
        $shop_menu = db("shop_menu")->column("shop_id");
        $pc_sets = db("pc_config")->column("shop_id");
        if (empty($shop_menu)) {
            $shop_menu = array();
        }
        foreach ($list as $key => $value) {
            if (!empty($parents) && in_array($value['parent_id'], array_keys($parents))) {
                $list[$key]['parent_name'] = $parents[$value['parent_id']];
            }
            if(in_array($value['id'], $shop_menu)){
                $list[$key]["has_menu"] = 1;
            }else{
                $list[$key]["has_menu"] = 0;
            }
            if(in_array($value["id"], $pc_sets )){
                $list[$key]["pc_set"] = 1;
            }else{
                $list[$key]["pc_set"] = 0;
            }
        }
        $this->ajax(array('pageData' => $list, 'total' => $total, "draw" => $draw));
    }

    /**
     * 添加
     */
    public function add(){
        $parents = db("shop")->where(array("parent_id" => array("eq", 0)))->select();
        $apis = db("api_template")->field("id, name, api_version")->select();
        $this->assign("parents", $parents);
        $this->assign("apis", $apis);
        echo $this->fetch();
    }

    /**
     * 添加操作
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addPost(){
        if (request()->isPost()) {
            $shop_name = input("shop_name");
            $parent_id = input("parent_id/d");
            $api_version = input("api_version");
            $extra_config = htmlspecialchars_decode(input('extra_config'));
            $account = input("account");
            $password = input("password");
            $start_time = input("start_time/s");
            $expire_time = input("expire_time/s");
            if (empty($parent_id)) {
                $this->error("请选择上级门店");
            }
            if (empty($api_version)) {
                $this->ajax_error("请选择api版本");
            }
            if (empty($shop_name)) {
                $this->ajax_error("店铺名称不能为空");
            }
            $is_exist = db("shop")->where(array("shop_name" => array("eq", $shop_name), "parent_id" => array("gt", 0)))->count(1);
            if (!empty($is_exist)) {
                $this->ajax_error("店铺名称已存在");
            }

            if (empty($start_time) || empty($expire_time)) {
                $this->ajax_error("请选择开始结束时间");
            }
            if (strtotime($start_time) > strtotime($expire_time)) {
                $this->ajax_error("开始时间不能大于结束时间");
            }
            $this->verifyUnique($account);
            $shop_id = db("shop")->insertGetId(array("shop_name" => $shop_name, "parent_id" => $parent_id, "api_version" => $api_version,'extra_config' => $extra_config, "start_time" => strtotime($start_time), "expire_time" => strtotime($expire_time)));
            if (empty($shop_id)) {
                $this->ajax_error("失败");
            }

            $this->shopInit($shop_id, $account, $password);
            db("shop")->where(array("id" => array("eq", $shop_id)))->update(array("shop_code" => date("mdY") . $shop_id));

            $this->ajax_success("成功");
        }
    }

    /**
     * 验证管理员账号唯一
     * @param $account 账号
     */
    private function verifyUnique($account){
        $count = db("admin")->where(array("account" => array("eq", $account)))->count(1);
        if ($count > 0) {
            $this->ajax_error("账号已经存在");
        }
    }

    /**
     *  新增店铺后 需要初始化的数据
     * @param $shop_id
     * @param $account
     * @param $password
     */
    private function shopInit($shop_id, $account, $password) {

        //添加店铺管理员账号
        db("admin")->insert(array("name" => "shop_owner", 'account' => $account, "password" => md5($password), "shop_id" => $shop_id, 'is_shop_admin'=>1));
        //添加滑门
        $data = config("sliding_door");
        foreach ($data as $key => $value) {
            $data[$key]['shop_id']=$shop_id;
        }
        db("sliding_door")->insertAll($data);
        //新增系统设置
        $data = config("system_set");
        foreach ($data as $key => $value) {
            $data[$key]['shop_id']=$shop_id;
        }
        db("system_set")->insertAll($data);
    }

    /**
	 * 获取api 模板
	 */
    public function  getApiTemplate(){
        $api_version = input("api_version");
        $template = db("api_template")->where(array("api_version" => array("eq", $api_version)))->value("template");
        if(empty($template)){
            $this->ajax_error("无模板");
        }else{
            $this->ajax_success('成功',$template);
        }
    }


    /**
     * 修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit(){
        $shop_id = input("id/d");
        if (empty($shop_id)) {
            $this->ajax_error("参数错误");
        }
        $model = db("shop")->find($shop_id);
        if (empty($model)) {
            $this->ajax_error("店铺不存在");
        }
        if (empty($model["start_time"])) {
            $model["start_time"] = time();
        }
        if (empty($model["expire_time"])) {
            $model["expire_time"] = time();
        }
        $shops = db("shop")->where(array("parent_id" => array("eq", 0)))->column("id, shop_name");
        $apis = db("api_template")->field("id,name,api_version")->select();
        $this->assign("parents", $shops);
        $this->assign("model", $model);
        $this->assign("apis", $apis);
        echo $this->fetch();
    }

    /**
     * 修改操作
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editPost(){
        if(request()->isPost()){//提交
            $shop_id = input("id/d");
            $shop_name = input("shop_name/s");
            $start_time = input("start_time/s");
            $expire_time = input("expire_time/s");

            $shop = db("shop")->find($shop_id);

            if (empty($start_time) || empty($expire_time)) {
                $this->ajax_error("请选择开始结束时间");
            }
            if (strtotime($start_time) > strtotime($expire_time)) {
                $this->ajax_error("开始时间不能大于结束时间");
            }
            $update_data = array("start_time" => strtotime($start_time), "expire_time" => strtotime($expire_time));
            if ($shop["api_version"] != "qingniao") {
                $is_exist = db("shop")->where(array("shop_name" => array("eq", $shop_name), "id" => array("neq", $shop_id), "parent_id" => array("gt", 0)))->count(1);
                if ($is_exist > 0){
                    $this->ajax_error("门店名称已经存在");
                }
                $update_data["shop_name"] = $shop_name;
				$update_data["extra_config"] = htmlspecialchars_decode(input("extra_config"));
            }

            $update_res = db("shop")->where(array("id" => array("eq", $shop_id)))->update($update_data);
            if ($update_res === false) {
                $this->ajax_error("失败");
            }
            cache("ExtraConfig_" . $shop_id,null);
            $this->ajax_success("成功");
        }
    }

    /**
     * 删除门店
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function delete(){
        $id = input("id/d");
        if (empty($id)) {
            $this->error("参数错误");
        }
        $model = db("shop")->where(array("id" => array("eq", $id)))->find();
        if(empty($model)){//父类
            $this->ajax_error("参数错误");
        }
        $interface = db("interface")->where(array("shop_id" => $id))->count(1);
        if (!empty($interface)) {
            $this->ajax_error("该店铺下有会员数据，无法删除");
        }
        $del_res = db("shop")->where(array("id" => array("eq", $id)))->delete();
        if (empty($del_res)) {
            $this->ajax_error("失败");
        }
        cache("AnkeConfig_" . $id,null);
        $this->ajax_success("成功");
    }


    /**
     * 设置菜单
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function setMenu(){
        $id = input("id/d");
        $post_data = input("post.");
        if (empty($id)) {
            $shop_id = input("shop_id/d");
            if (empty($shop_id)) {
                $this->ajax_error("失败！");
            }
            $menu_id = db("shop_menu")->where(array("shop_id" => array("eq", $shop_id)))->value("id");
            if (empty($menu_id)) {
                $data = db('shop_menu')->insert($post_data);
            } else {
                $post_data['id'] = $menu_id;
                $data = db('shop_menu')->where(array("id" => array("eq", $menu_id), "shop_id" => array("eq", $shop_id)))->update(array(
                    "pool_1" => input("pool_1"),
                    "pool_2" => input("pool_2"),
                    "pool_3" => input("pool_3"),
                ));
            }
            $this->ajax_success("成功！",$data);
        }else{
            $shop = db("shop")->where(array("id" => array("eq", $id)))->find();
            if (empty($shop) || empty($shop['parent_id'])) {
                $this->ajax_error("品牌无需设置！");
            }
            $menu = sp_get_all_menu();
            $this->assign("menus", $menu);
            $shop_menu = db("shop_menu")->where(array("shop_id" => array("eq", $id)))->find();
            $this->assign("model", $shop_menu);
            $this->assign("shop_id",$id);
            echo $this->fetch();
        }
    }
	public function smallappAuth(){
		$is_submit=input("is_submit");
		if(empty($is_submit)){
			$this->assign("shop",db("shop")->field("id,shop_name")->find(input("id")));
			$this->assign("auths",config("smallapp_auth.member_auth"));
			$has_auths=db("SmallappAuth")->where("shop_id=".input("id"))->value("auth_code");
			if(empty($has_auths)){
				$this->assign("has_auths",[]);
			}else{
				$this->assign("has_auths",explode(",", $has_auths));
			}
			echo $this->fetch();
		}else{
			$shop_id=input("shop_id");
			db("SmallappAuth")->where("shop_id=$shop_id")->delete();
			if(!isset($_POST['auth_code'])||empty($_POST['auth_code'])){
				$this->ajax_success("成功");
			}
			$auth_code=$_POST['auth_code'];
			if(is_array($auth_code)){
				db("SmallappAuth")->insert(array(
					"shop_id"=>$shop_id,
					"auth_code"=>implode(",", $auth_code),
				));	
			}
			$this->ajax_success("成功");
		}
	}

    /**
     * 设置店铺pc机器上的配置
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setPcConfig(){
        $shop_id = input("id/d");
        if (empty($shop_id)) {
            $this->ajax_error("参数错误");
        }else{
            $shop = db("shop")->where(array("id" => $shop_id))->find();
            if (empty($shop) || empty($shop['parent_id'])) {
                $this->ajax_error("品牌无需设置");
            }
            $model = db("pc_config")->where(array("shop_id" => $shop_id))->find();
            if (empty($model)) {
                $model = array("shop_id" => $shop_id, "server_url" => "", "shop_code" => "", "browser" => 1, "pic_version" => 0, "locker_version" => 1, "card_keys" => "", "is_locker" => 1, "gym_type" => 0, "off_line_in" => 0, "off_line" => 0, "model_count" => 1, "reader_version" => 0,"model_store_type" => 0);
                $this->assign("id", 0);
            }else{
                $this->assign("id", $model['id']);
            }
            $this->assign("model", $model);
        }
        $this->assign("shop", db("shop")->find($shop_id));
        echo $this->fetch();
    }

    /**
     * PC设置操作
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setPcConfigPost(){
        $shop_id = input("id/d");
        $card_keys = input("card_keys/s");
        if (empty($card_keys)) {
            $this->ajax_error("卡密钥不能为空");
        }
        if (empty($shop_id)) {
            $res = db("pc_config")->insert(
                array(
                    "server_url"    => input("server_url"),
                    "shop_code"     => input("shop_code"),
                    "shop_id"       => input("shop_id"),
                    "browser"       => input("browser"),
                    "pic_version"   => input("pic_version"),
                    "locker_version"=> input("locker_version"),
                    "card_keys"     => input("card_keys"),
                    "is_locker"     => input("is_locker"),
                    "gym_type"      => input("gym_type"),
                    "off_line"      => input("off_line"),
                    "off_line_in"   => input("off_line_in"),
                    "model_count"   => input("model_count"),
                    "reader_version" => input("reader_version"),
                    "model_store_type"=>input("model_store_type"),
                )
            );
        }else{
            $res = db("pc_config")->where(array("id" => $shop_id))->update(
                array(
                    "server_url"    => input("server_url"),
                    "shop_code"     => input("shop_code"),
                    "browser"       => input("browser"),
                    "pic_version"   => input("pic_version"),
                    "locker_version"=> input("locker_version"),
                    "card_keys"     => input("card_keys"),
                    "is_locker"     => input("is_locker"),
                    "gym_type"      => input("gym_type"),
                    "off_line"      => input("off_line"),
                    "off_line_in"   => input("off_line_in"),
                    "model_count"   => input("model_count"),
                    "reader_version" => input("reader_version"),
                    "model_store_type"=>input("model_store_type"),
                )
            );
        }
        if ($res === false) {
            $this->ajax_error("失败");
        }
        return $this->ajax_success("成功");
    }

    /**
     * 快捷登陆
     */
    public function quickLogin()
    {
        $shop_id = input("id/d");
        if (empty($shop_id)) {
            $this->error("参数错误");
        }
        $admin = db("admin")->where(array("shop_id" => $shop_id, "is_shop_admin" => 1))->find();
        if (empty($admin)) {
            $this->error("该店铺未获取到管理员账号");
        }
        session("Admin", $admin);
        $this->redirect("/Admin/Main/index");
    }

    /**
     * 同步勤鸟
     */
    public function syncShop() {
        $shop_id = input("id/d");
        if (empty($shop_id)) {
            $this->ajax_error("参数错误");
        }
        $shop = db("shop")->find($shop_id);
        if (empty($shop)) {
            $this->ajax_error("参数错误");
        }
        if ($shop['api_version'] != 'qingniao') {
            $this->ajax_error("参数错误");
        }
        $time = time();
        $sign = md5($shop_id. $time);
        $params = array("shop_id" => $shop_id, "shop_name" => $shop["shop_name"], "api_version" => $shop["api_version"], "parent_id" => $shop["parent_id"], "time" => $time, "sign" => $sign);
        $url = "http://zwzlcloud.ocmcom.com/api/QnSync/SyncShop";
        $post_res = post_submit_json($url, $params);
        if (!empty($post_res) || !empty($post_res["flag"])) {
            $this->ajax_success($post_res);
        } else {
            $this->ajax_error($post_res['msg']);
        }
    }

    /**
     * 品牌列表
     */
    public function brand() {
        $auth_group = sp_get_auth_menu_3("20001004");
        $this->assign("menus", $auth_group);
        echo $this->fetch();
    }

    public function ajaxBrand() {
        $shop_name = input("shop_name/s");
        $draw = input("draw",0) + 1; //请求时间

        $where = array("parent_id" => array("eq", 0));
        if (!empty($shop_name)) {
            $where["shop_name"] = array("like", "%{$shop_name}%");
        }
        $total = db("shop")->where($where)->count(1);
        $list = db("shop")->where($where)->order($this->get_order())->limit($this->get_limit())->select();
        $this->ajax(array('pageData' => $list, 'total' => $total, "draw" => $draw));
    }

    public function brandAdd() {
        echo $this->fetch();
    }

    public function brandAddPost() {
        $shop_name = input("shop_name");
		$brand_code=input("brand_code");
        if (empty($shop_name)) {
            $this->ajax_error("品牌名称不能为空");
        }
        $is_exist = db("shop")->where(array("shop_name" => array("eq", $shop_name), "parent_id" => 0))->find();
        if (!empty($is_exist)) {
            $this->ajax_error("品牌名已存在");
        }
		$brand_code_count = db("shop")->where("brand_code='$brand_code'")->count(1);
        if (!empty($brand_code_count)) {
            $this->ajax_error("品牌代码已存在");
        }
        $add_res = db("shop")->insert(array("shop_name" => $shop_name,"brand_code"=>$brand_code, "parent_id" => 0, "api_version" => null));
        if (empty($add_res)) {
            $this->ajax_error("添加失败");
        }
        $this->ajax_success("添加成功");
    }

    public function brandEdit() {
        $id = input("id/d");
        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $shop = db("shop")->find($id);
        if (empty($shop)) {
            $this->ajax_error("参数错误");
        }
        if (!empty($shop["parent"])) {
            $this->ajax_error("参数错误");
        }
        $this->assign("shop", $shop);
        echo $this->fetch();
    }

    public function brandEditPost() {
        $id = input("id/d");
        $shop_name = input("shop_name");
        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $shop = db("shop")->find($id);
        if (empty($shop)) {
            $this->ajax_error("参数错误");
        }
        if (!empty($shop["parent"])) {
            $this->ajax_error("参数错误");
        }
        if (empty($shop_name)) {
            $this->ajax_error("品牌名称不能为空");
        }
        $is_exist = db("shop")->where(array("shop_name" => array("eq", $shop_name), "parent_id" => 0, "id" => array("neq", $id)))->find();
        if (!empty($is_exist)) {
            $this->ajax_error("品牌名已存在");
        }
        $update_res = db("shop")->where(array("id" => $id))->update(array("shop_name" => $shop_name));
        if ($update_res === false) {
            $this->ajax_error("添加失败");
        }
        $this->ajax_success("添加成功");
    }
	/**
	 * 停用
	 * */
	public function stop(){
		if(request()->isPost()){
			$id=input("id/d",0);
			db("Shop")->where("id=$id")->setField(array("status"=>0));
			cache("ShopStatus_".$id,0);
			$this->ajax_success("成功");
			
		}
	}
	/**
	 * 启用
	 * */
	public function start(){
		if(request()->isPost()){
			$id=input("id/d",0);
			db("Shop")->where("id=$id")->setField(array("status"=>1));
			cache("ShopStatus_".$id,1);
			$this->ajax_success("成功");
		}
	}
    public function brandDelete() {
        $id = input("id/d");
        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $shop = db("shop")->find($id);
        if (empty($shop)) {
            $this->ajax_error("参数错误");
        }
        if (!empty($shop["parent"])) {
            $this->ajax_error("参数错误");
        }
        $shop_children = db("shop")->where(array("parent_id" => $id))->count(1);
        if (!empty($shop_children)) {
            $this->ajax_error("该品牌下已存在店铺，请删除店铺后操作");
        }
        $del_res = db("shop")->delete($id);
        if (empty($del_res)) {
            $this->ajax_error("删除失败");
        }
        $this->ajax_success("删除成功");
    }
}